package com.mz.ozy.widget.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.mz.ozy.R;
import com.mz.ozy.bean.CheckBean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class CheckDialog extends Dialog {
    private Context mContext;
    OnClickListener mOnClickListener;

    private FileOutputStream fos;
    InputStream is;
    ProgressBar progressBar;
    private CheckBean checkBean;

    public CheckDialog(@NonNull Context context, CheckBean checkBean) {
        super(context, R.style.dialogtheme);
        this.checkBean = checkBean;
        this.mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_alert, null);
        setContentView(view);

        TextView beta_title = view.findViewById(R.id.beta_title);
        TextView beta_upgrade_feature = view.findViewById(R.id.beta_upgrade_feature);
        beta_upgrade_feature.setText(checkBean.getVersionMapaz().getVdescribe());
        beta_title.setText(checkBean.getVersionMapaz().getVname() + "版本更新内容");

        TextView dialog_cancel = view.findViewById(R.id.dialog_cancel);
        TextView dialog_ensure = view.findViewById(R.id.dialog_ensure);
        View line = view.findViewById(R.id.line);
        LinearLayout liBut = view.findViewById(R.id.ll_button);
        LinearLayout llPro = view.findViewById(R.id.ll_pro);

        progressBar = view.findViewById(R.id.progress_horizontal);

        if (checkBean.getVersionMapaz().getUpdateFlag() == 9) {
            setCanceledOnTouchOutside(false);
            setCancelable(false);
            dialog_cancel.setVisibility(View.GONE);

        }

        dialog_ensure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                liBut.setVisibility(View.GONE);
                line.setVisibility(View.GONE);
                llPro.setVisibility(View.VISIBLE);
                run();
                if (mOnClickListener != null) {
                    mOnClickListener.onClick();
                }
            }
        });
        dialog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });


    }

    private void run() {
        new Thread(new Runnable() {
            public void run() {
                //执行耗时操作
                OkHttpClient client = new OkHttpClient();
                String url = checkBean.getVersionMapaz().getUpdatePath();
//                url = "https://beibi.szfysoft.com/BB.VIP1.0.2.apk";
                Request request = new Request.Builder().get().url(url).build();
                try {
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        Log.d("apk状态==>", "开始下载apk");
                        //获取内容总长度
                        long contentLength = response.body().contentLength();
                        //设置最大值
                        progressBar.setMax((int) contentLength);

                        //保存到sd卡
                        File apkFile = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".apk");
                        fos = new FileOutputStream(apkFile);
                        //获得输入流
                        is = response.body().byteStream();
                        //定义缓冲区大小
                        byte[] bys = new byte[1024];
                        int progress = 0;
                        int len = -1;
                        while ((len = is.read(bys)) != -1) {
                            try {
                                Thread.sleep(1);
                                fos.write(bys, 0, len);
                                fos.flush();
                                progress += len;
                                //设置进度
                                progressBar.setProgress(progress);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        }
                        //下载完成,提示用户安装
                        installApk(apkFile);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {

                    //关闭io流
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        is = null;
                    }
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        fos = null;
                    }

                }

            }
        }).start();
    }


    private void installApk(File apkFile) {
        setPermission(apkFile.getAbsolutePath());
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        //Android 7.0以上要使用FileProvider
        if (Build.VERSION.SDK_INT >= 24) {
            //File file = (new File(pathstr));
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(mContext, mContext.getApplicationInfo().packageName + ".fileprovider", apkFile);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {

            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);
    }

    private void setPermission(String absolutePath) {
        String[] command = {"chmod", "777", absolutePath};
        ProcessBuilder builder = new ProcessBuilder(command);
        try {
            builder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public interface OnClickListener {
        void onClick();
    }

}
